/**
 * 测试运行器
 * 统一管理和运行所有测试套件
 */

const { runTests } = require('./api.test.js')
const { runDetailedTests } = require('./detailed-api.test.js')
const { testToolDeployment } = require('./tool-deployment.test.js')

// 测试运行配置
const TEST_CONFIG = {
  // 测试环境检查
  requiredEnvVars: ['DATABASE_URL', 'FORCE_DATABASE'],
  
  // 服务器检查
  serverUrl: 'http://localhost:3000',
  serverCheckTimeout: 5000,
  
  // 测试选项
  runBasicTests: true,
  runDetailedTests: true,
  runDeploymentTests: true,
  runPerformanceTests: true,
  
  // 输出选项
  verbose: true,
  saveResults: true
}

// 检查环境变量
function checkEnvironment() {
  console.log('🔍 检查测试环境...')

  // 尝试加载.env文件
  try {
    require('dotenv').config()
  } catch (error) {
    // dotenv可能未安装，尝试手动读取.env文件
    try {
      const fs = require('fs')
      const path = require('path')
      const envPath = path.join(process.cwd(), '.env')
      const envContent = fs.readFileSync(envPath, 'utf8')

      envContent.split('\n').forEach(line => {
        const [key, value] = line.split('=')
        if (key && value) {
          process.env[key.trim()] = value.trim().replace(/^["']|["']$/g, '')
        }
      })
    } catch (readError) {
      console.warn('⚠️ 无法读取.env文件，使用系统环境变量')
    }
  }

  const missingVars = TEST_CONFIG.requiredEnvVars.filter(varName => !process.env[varName])

  if (missingVars.length > 0) {
    console.error('❌ 缺少必要的环境变量:')
    missingVars.forEach(varName => console.error(`  - ${varName}`))
    console.error('\n请确保.env文件存在并包含以下变量:')
    TEST_CONFIG.requiredEnvVars.forEach(varName => {
      console.error(`  ${varName}="your-value"`)
    })
    return false
  }

  console.log('✅ 环境变量检查通过')
  console.log(`   DATABASE_URL: ${process.env.DATABASE_URL ? '已设置' : '未设置'}`)
  console.log(`   FORCE_DATABASE: ${process.env.FORCE_DATABASE}`)
  return true
}

// 检查服务器状态
async function checkServer() {
  console.log('🔍 检查服务器状态...')
  
  const http = require('http')
  
  return new Promise((resolve) => {
    const req = http.get(TEST_CONFIG.serverUrl + '/api/tools', { timeout: TEST_CONFIG.serverCheckTimeout }, (res) => {
      if (res.statusCode === 200) {
        console.log('✅ 服务器运行正常')
        resolve(true)
      } else {
        console.error(`❌ 服务器响应异常: ${res.statusCode}`)
        resolve(false)
      }
    })
    
    req.on('error', (error) => {
      console.error(`❌ 服务器连接失败: ${error.message}`)
      console.error('请确保开发服务器正在运行: npm run dev')
      resolve(false)
    })
    
    req.on('timeout', () => {
      console.error('❌ 服务器响应超时')
      resolve(false)
    })
  })
}

// 运行预检查
async function runPreChecks() {
  console.log('🚀 开始测试预检查...\n')
  
  // 检查环境
  if (!checkEnvironment()) {
    return false
  }
  
  // 检查服务器
  if (!await checkServer()) {
    return false
  }
  
  console.log('✅ 预检查完成\n')
  return true
}

// 运行所有测试
async function runAllTests() {
  const startTime = Date.now()
  
  try {
    // 预检查
    if (!await runPreChecks()) {
      console.error('❌ 预检查失败，终止测试')
      process.exit(1)
    }
    
    console.log('=' .repeat(60))
    console.log('🧪 开始API测试套件')
    console.log('=' .repeat(60))
    
    let allTestsPassed = true
    let basicResults = null
    let detailedResults = null
    let deploymentResults = null

    // 运行基础测试
    if (TEST_CONFIG.runBasicTests) {
      console.log('\n📋 运行基础API测试...')
      try {
        basicResults = await runTests()
        if (!basicResults.success) {
          allTestsPassed = false
        }
      } catch (error) {
        console.error('基础测试执行失败:', error)
        allTestsPassed = false
      }
    }

    // 运行详细测试
    if (TEST_CONFIG.runDetailedTests) {
      console.log('\n📋 运行详细API测试...')
      try {
        detailedResults = await runDetailedTests()
        if (!detailedResults.success) {
          allTestsPassed = false
        }
      } catch (error) {
        console.error('详细测试执行失败:', error)
        allTestsPassed = false
      }
    }

    // 运行部署测试
    if (TEST_CONFIG.runDeploymentTests) {
      console.log('\n📋 运行工具部署测试...')
      try {
        deploymentResults = await testToolDeployment()
        if (!deploymentResults.success) {
          allTestsPassed = false
        }
      } catch (error) {
        console.error('部署测试执行失败:', error)
        allTestsPassed = false
      }
    }
    
    // 测试总结
    const endTime = Date.now()
    const totalTime = endTime - startTime
    
    console.log('\n' + '=' .repeat(60))
    console.log('📊 测试套件总结')
    console.log('=' .repeat(60))
    console.log(`总耗时: ${totalTime}ms`)
    console.log(`测试环境: ${process.env.NODE_ENV || 'development'}`)
    console.log(`数据库: ${process.env.FORCE_DATABASE === 'true' ? 'PostgreSQL' : 'JSON文件'}`)

    // 显示详细统计
    if (basicResults) {
      console.log(`基础测试: ${basicResults.passed}/${basicResults.total} 通过 (${((basicResults.passed / basicResults.total) * 100).toFixed(1)}%)`)
    }
    if (detailedResults) {
      console.log(`详细测试: ${detailedResults.passed}/${detailedResults.total} 通过 (${((detailedResults.passed / detailedResults.total) * 100).toFixed(1)}%)`)
    }
    if (deploymentResults) {
      console.log(`部署测试: ${deploymentResults.passed}/${deploymentResults.total} 通过 (${((deploymentResults.passed / deploymentResults.total) * 100).toFixed(1)}%)`)
    }

    if (allTestsPassed) {
      console.log('🎉 所有测试套件通过！')

      // 保存测试结果
      if (TEST_CONFIG.saveResults) {
        await saveTestResults({
          timestamp: new Date().toISOString(),
          duration: totalTime,
          status: 'PASSED',
          environment: process.env.NODE_ENV || 'development',
          database: process.env.FORCE_DATABASE === 'true' ? 'PostgreSQL' : 'JSON',
          basicResults: basicResults,
          detailedResults: detailedResults,
          deploymentResults: deploymentResults
        })
      }

      process.exit(0)
    } else {
      console.log('💥 部分测试失败')

      // 保存失败结果
      if (TEST_CONFIG.saveResults) {
        await saveTestResults({
          timestamp: new Date().toISOString(),
          duration: totalTime,
          status: 'FAILED',
          environment: process.env.NODE_ENV || 'development',
          database: process.env.FORCE_DATABASE === 'true' ? 'PostgreSQL' : 'JSON',
          basicResults: basicResults,
          detailedResults: detailedResults,
          deploymentResults: deploymentResults
        })
      }

      process.exit(1)
    }
    
  } catch (error) {
    console.error('测试运行器执行失败:', error)
    process.exit(1)
  }
}

// 保存测试结果
async function saveTestResults(results) {
  const fs = require('fs').promises
  const path = require('path')
  
  try {
    const resultsDir = path.join(__dirname, 'results')
    
    // 确保结果目录存在
    try {
      await fs.access(resultsDir)
    } catch {
      await fs.mkdir(resultsDir, { recursive: true })
    }
    
    // 保存结果文件
    const filename = `test-results-${new Date().toISOString().replace(/[:.]/g, '-')}.json`
    const filepath = path.join(resultsDir, filename)
    
    await fs.writeFile(filepath, JSON.stringify(results, null, 2))
    console.log(`📄 测试结果已保存: ${filepath}`)
    
    // 更新最新结果
    const latestPath = path.join(resultsDir, 'latest.json')
    await fs.writeFile(latestPath, JSON.stringify(results, null, 2))
    
  } catch (error) {
    console.error('保存测试结果失败:', error)
  }
}

// 显示帮助信息
function showHelp() {
  console.log(`
🧪 API测试套件使用说明

用法:
  node tests/test-runner.js [选项]

选项:
  --basic-only     只运行基础测试
  --detailed-only  只运行详细测试
  --deployment-only 只运行部署测试
  --no-save        不保存测试结果
  --help           显示此帮助信息

环境要求:
  1. 开发服务器必须运行在 http://localhost:3000
  2. 环境变量 DATABASE_URL 必须设置
  3. 环境变量 FORCE_DATABASE 必须设置为 'true'

示例:
  npm test                    # 运行所有测试
  npm run test:basic          # 只运行基础测试
  npm run test:detailed       # 只运行详细测试
  npm run test:deployment     # 只运行部署测试
  
启动开发服务器:
  npm run dev

检查测试结果:
  cat tests/results/latest.json
`)
}

// 处理命令行参数
function parseArgs() {
  const args = process.argv.slice(2)
  
  if (args.includes('--help')) {
    showHelp()
    process.exit(0)
  }
  
  if (args.includes('--basic-only')) {
    TEST_CONFIG.runBasicTests = true
    TEST_CONFIG.runDetailedTests = false
    TEST_CONFIG.runDeploymentTests = false
  }

  if (args.includes('--detailed-only')) {
    TEST_CONFIG.runBasicTests = false
    TEST_CONFIG.runDetailedTests = true
    TEST_CONFIG.runDeploymentTests = false
  }

  if (args.includes('--deployment-only')) {
    TEST_CONFIG.runBasicTests = false
    TEST_CONFIG.runDetailedTests = false
    TEST_CONFIG.runDeploymentTests = true
  }
  
  if (args.includes('--no-save')) {
    TEST_CONFIG.saveResults = false
  }
}

// 主函数
async function main() {
  parseArgs()
  
  console.log('🧪 API测试套件启动')
  console.log(`版本: 1.0.0`)
  console.log(`时间: ${new Date().toLocaleString()}`)
  console.log(`环境: ${process.env.NODE_ENV || 'development'}`)
  
  await runAllTests()
}

// 运行测试
if (require.main === module) {
  main().catch(console.error)
}

module.exports = {
  runAllTests,
  checkEnvironment,
  checkServer,
  saveTestResults
}
